package org.procat.porrapp;

import java.util.Map;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class StartPorrapp extends Activity implements OnItemClickListener {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.start_porrapp);   
		
		ListView llista = (ListView) findViewById(R.id.listPorres);
		llista.setOnItemClickListener(this);
		
		actualitzaLlista();
	}

	public void novaPorra (View v) 
	{
		Intent i = new Intent(this, PorraMainActivity.class);
		i.putExtra("porra", "nova");
		startActivity(i);      	
	}
	public void actualitzaLlista()
	{ 
		ListView llista = (ListView) findViewById(R.id.listPorres);
		ArrayAdapter<String> llistaAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);

		SharedPreferences prefs = getSharedPreferences("PorraData", 0);
		Map<String, ?> mapaLlista = prefs.getAll();

		for(Map.Entry<String, ?> entry : mapaLlista.entrySet())
		{
			String key = entry.getKey();
			if (key.startsWith("Porra") && ! key.contains("."))
				llistaAdapter.add( key + " ==> "+ entry.getValue());
		}    	

		llista.setAdapter(llistaAdapter);
	}

	public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
		String codiPorra = ((TextView) v).getText().toString();
		codiPorra = codiPorra.substring(5, codiPorra.indexOf(" ==> "));
		
		Toast.makeText(getApplicationContext(), "Obrint Porra #" + codiPorra + "#", Toast.LENGTH_LONG).show(); 
		
		
		Intent i = new Intent(this, PorraMainActivity.class);
		i.putExtra("porra", codiPorra);
		startActivity(i);      	
	}

}
